﻿using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using Red.Controls.Extensions;
using Red.Controls.Shell;

namespace Red.Controls.DataDriven
{
    [InteropControl( "Res:ITexture", "Res:IMaterial", "Res:animRig", "Res:animAnimSet", "Res:CMesh", "Res:scenePrefab", "Res:animCharacterDef")]
    public partial class ResourceBox : UserControl
    {
        #region Private Data

        private Brush _backgroundBrush;

        #endregion Private Data

        #region C-Tor

        public ResourceBox()
        {
            InitializeComponent();

            DragBroadcaster.OnDragStarted += DragBroadcaster_OnDragStarted;
            DragBroadcaster.OnDragEnded += DragBroadcaster_OnDragEnded;

            _textbox.PreviewDragEnter += ResourceTextBox_PreviewDragEnter;
            _textbox.PreviewDragOver += ResourceTextBox_PreviewDragOver;
            _textbox.Drop += ResourceTextBox_Drop;
        }

        #endregion C-Tor

        #region Event handlers 

        // DragBroadcaster events handling to indicate it's a target for dropping
        private void DragBroadcaster_OnDragStarted( object sender, IDataObject draggedData )
        {
            _backgroundBrush = Background;
            Background = Brushes.LightGreen;
        }

        private void DragBroadcaster_OnDragEnded( object sender, IDataObject draggedData )
        {
            Background = _backgroundBrush;
        }

        // Apparently TextBox already has some handling for drag'n'drop for strings,
        // so we need to override it with our own drag and drop (see https://peteohanlon.wordpress.com/2009/09/28/textbox-dragdrop-in-wpf/)
        private void ResourceTextBox_PreviewDragOver( object sender, DragEventArgs e )
        {
            e.Handled = true;
        }

        private void ResourceTextBox_PreviewDragEnter( object sender, DragEventArgs e )
        {
            e.Handled = true;
        }

        // Drop the resource
        private void ResourceTextBox_Drop( object sender, DragEventArgs e )
        {
            string[] paths = e.Data.GetFormats().Select( format => e.Data.GetData( format ).ToString() ).ToArray();
            if ( paths.Length > 1 )
            {
                RedMessageBox.Show( this, RedDialogType.Ok, "Property accepts just one value at a time." );
            }
            else
            {
                _textbox.Text = paths[ 0 ];
            }
        }
        
        #endregion Event handlers
    }
}
